package datastructure.hash;

import java.util.HashSet;
import java.util.Set;

/**
 * 快乐数
 */
public class LC202 {
    //时间复杂度偏高
    public boolean isHappy1(int n) {
        Set<Integer> set = new HashSet<>();
        while (n != 1) {
            set.add(n);
            n = getNextNumber(n);
            if (set.contains(n)) {
                return false;
            }
        }
        return true;
    }

    private int getNextNumber(int n) {
        int res = 0;
        while (n > 0) {
            int temp = n % 10;
            res += temp * temp;
            n = n / 10;
        }
        return res;
    }

    //快慢指针，反正我是想不到，不过也有可能想到，跟环有关的东西都可以用快慢指针
    public boolean isHappy(int n) {
        int slow = n;
        int fast = getNextNumber(n);
        while (fast != 1 && fast != slow) {
            slow = getNextNumber(slow);
            fast = getNextNumber(getNextNumber(fast));
        }
        return fast == 1;
    }
}
